package vip.xiaonuo.hontu.issued.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import vip.xiaonuo.hontu.issued.constant.HTConstant;
import vip.xiaonuo.hontu.issued.request.BatchAddPersonRequest;
import vip.xiaonuo.hontu.issued.request.BatchAddPersonRequest.PersonListDTO;
import vip.xiaonuo.hontu.issued.request.BatchDeletePersonRequest;
import vip.xiaonuo.hontu.issued.request.HTUpdatePersonRequest;
import vip.xiaonuo.hontu.issued.response.BatchAddPersonResponse;
import vip.xiaonuo.hontu.issued.response.BatchDeletePersonResponse;
import vip.xiaonuo.hontu.issued.response.HTBaseResponse;
import vip.xiaonuo.hontu.issued.util.HT_DEVICE_POST;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.facedoor.iservice.IFaceDoorDtoService;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.AddPersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.DeletePersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.DeviceStateResponse;
import vip.xiaonuo.facedoor.vo.dewo.GetPersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.GetPersonResponse;
import vip.xiaonuo.facedoor.vo.dewo.UpdatePersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.BaseResponse;
import vip.xiaonuo.facedoor.vo.haiqing.GetAndSetDoorCondition;
import vip.xiaonuo.facedoor.vo.haiqing.GetAndSetGeneralParamRequest;
import vip.xiaonuo.facedoor.vo.haiqing.GetAndSetSoundRequest;
import vip.xiaonuo.facedoor.vo.haiqing.HQAddPersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.OpenDoorRequest;
import vip.xiaonuo.facedoor.vo.haiqing.RebootDeviceRequest;
import vip.xiaonuo.facedoor.vo.haiqing.RequestHeader;
import vip.xiaonuo.facedoor.vo.haiqing.SetFactoryDefaultRequest;
import vip.xiaonuo.facedoor.vo.haiqing.SetSubscribeRequest;
import vip.xiaonuo.facedoor.vo.haiqing.SetSysTimeRequest;
import vip.xiaonuo.facedoor.vo.haiqing.SetUserPwdRequest;

@Service(value = RuleConstant.HT + RuleConstant.FACEDOOR_DTO)
@Slf4j
public class HTFaceDoorDtoServiceImpl implements IFaceDoorDtoService {


    @Override
    public DeviceStateResponse getDeviceState(String uri) throws Exception {
        return null;
    }

    @Override
    public ReturnJson addPerson(String uri, AddPersonRequest addPersonRequest) throws Exception {

        String imagePath = ConstantContextHolder.getSysConfig("SNOWY_FILE_UPLOAD_PATH_FOR_WINDOWS", String.class, true);
        if (StringUtils.isBlank(addPersonRequest.getFaceFeatureImgPath())) {
            throw new ServiceException(500, "人脸图片未上传，请重新上传人脸图片");
        }
        imagePath = imagePath + "/defaultBucket/" + addPersonRequest.getFaceFeatureImgPath();
        File file = new File(imagePath);
        if (!file.exists()) {
            throw new ServiceException(500, "人脸图片不存在，请重新上传人脸图片");
        }

        String imageUri = HT_DEVICE_POST.uploadImage(imagePath, addPersonRequest.getIp(), addPersonRequest.getPort());
        BatchAddPersonRequest batchAddPersonRequest = new BatchAddPersonRequest();
        BatchAddPersonRequest.PersonListDTO personListDTO = new PersonListDTO();
        batchAddPersonRequest.getPersonList().add(personListDTO);
        personListDTO.setImageUri(imageUri);
        personListDTO.setName(addPersonRequest.getName());
        personListDTO.setUuid(addPersonRequest.getPersonnelId());
        personListDTO.setOrgUuid(addPersonRequest.getOrgId());
        personListDTO.setType(Optional.ofNullable(HTConstant.personTypes.get(addPersonRequest.getPersonType())).orElse(1));
        BatchAddPersonResponse batchAddPersonResponse = HT_DEVICE_POST.postJson(HTConstant.batchAddPerson, addPersonRequest.getIp(), addPersonRequest.getPort(), batchAddPersonRequest, BatchAddPersonResponse.class);
        if (ObjectUtil.equal(batchAddPersonResponse.getCode(), 0)) {
            if (CollectionUtils.isNotEmpty(batchAddPersonResponse.getData().getSuccesses())) {
                ReturnJson returnJson = new ReturnJson();
                returnJson.success("0000", "success！");
                return returnJson;
            } else {
                throw new ServiceException(
                        500,
                        addPersonRequest.getName() + " 失败信息： code:"
                                + batchAddPersonResponse.getCode()
                                + " message:  批量添加人员失败！"
                                + JSON.toJSONString(batchAddPersonResponse));
            }

        } else {
            throw new ServiceException(
                    500,
                    addPersonRequest.getName() + " 失败信息： code:"
                            + batchAddPersonResponse.getCode()
                            + " message:  "
                            + JSON.toJSONString(batchAddPersonResponse));
        }
    }


    private static ReturnJson addOrUpdate(String uri, HQAddPersonRequest addPersonRequest, RequestHeader addPersonRequest1, String message, String type) throws Exception {
        return null;
    }

    @Override
    public ReturnJson deletePerson(String uri, DeletePersonRequest deletePersonRequest) throws Exception {
        BatchDeletePersonRequest batchDeletePersonRequest = new BatchDeletePersonRequest();
        List<String> uuidList = batchDeletePersonRequest.getUuidList();
        uuidList.add(deletePersonRequest.getPersonnelId());
        BatchDeletePersonResponse deletePersonResponse = HT_DEVICE_POST.postJson(HTConstant.batchDeletePerson, deletePersonRequest.getIp(), deletePersonRequest.getPort(), batchDeletePersonRequest, BatchDeletePersonResponse.class);
        if (ObjectUtil.equal(deletePersonResponse.getCode(), 0)) {
            if (CollectionUtils.isNotEmpty(deletePersonResponse.getData().getSuccesses())) {
                ReturnJson returnJson = new ReturnJson();
                returnJson.success("0000", "success！");
                return returnJson;
            } else if (CollectionUtils.isNotEmpty(deletePersonResponse.getData().getFailures())) {
                // 人员已经不存在
                if (ObjectUtil.equal(deletePersonResponse.getData().getFailures().get(0).getCode(), 101012)) {
                    ReturnJson returnJson = new ReturnJson();
                    returnJson.success("0000", "success！");
                    return returnJson;
                }
            } else {
                throw new ServiceException(
                        500,
                        deletePersonRequest.getPersonnelId() + " 失败信息： code:"
                                + deletePersonResponse.getCode()
                                + " message:  删除人员失败！"
                                + JSON.toJSONString(deletePersonResponse));
            }

        } else {
            throw new ServiceException(
                    500,
                    deletePersonRequest.getPersonnelId() + " 失败信息： code:"
                            + deletePersonResponse.getCode()
                            + " message:  "
                            + JSON.toJSONString(deletePersonResponse));
        }
        ReturnJson returnJson = new ReturnJson();
        returnJson.success("0000", "success！");
        return returnJson;
    }

    @Override
    public ReturnJson deleteAllPerson(String uri, DeletePersonRequest deletePersonRequest) throws Exception {
        ReturnJson returnJson = new ReturnJson();
        returnJson.success("0000", "success！");
        return returnJson;
    }

    @Override
    public ReturnJson updatePerson(String uri, UpdatePersonRequest updatePersonRequest) throws Exception {
        String imagePath = ConstantContextHolder.getSysConfig("SNOWY_FILE_UPLOAD_PATH_FOR_WINDOWS", String.class, true);
        if (StringUtils.isBlank(updatePersonRequest.getFaceFeatureImgPath())) {
            throw new ServiceException(500, "人脸图片未上传，请重新上传人脸图片");
        }
        imagePath = imagePath + "/defaultBucket/" + updatePersonRequest.getFaceFeatureImgPath();
        File file = new File(imagePath);
        if (!file.exists()) {
            throw new ServiceException(500, "人脸图片不存在，请重新上传人脸图片");
        }

        String imageUri = HT_DEVICE_POST.uploadImage(imagePath, updatePersonRequest.getIp(), updatePersonRequest.getPort());
        HTUpdatePersonRequest htUpdatePersonRequest = new HTUpdatePersonRequest();
        htUpdatePersonRequest.setUuid(updatePersonRequest.getPersonnelId());
        htUpdatePersonRequest.setImageUri(imageUri);
        htUpdatePersonRequest.setType(Optional.ofNullable(HTConstant.personTypes.get(updatePersonRequest.getPersonType())).orElse(1));
        htUpdatePersonRequest.setName(updatePersonRequest.getName());
        htUpdatePersonRequest.setOrgUuid(updatePersonRequest.getOrgId());
        HTBaseResponse batchUpdatePersonResponse = HT_DEVICE_POST.postJson(HTConstant.updatePerson, updatePersonRequest.getIp(), updatePersonRequest.getPort(), htUpdatePersonRequest, HTBaseResponse.class);
        if (ObjectUtil.equal(batchUpdatePersonResponse.getCode(), 0)) {
            ReturnJson returnJson = new ReturnJson();
            returnJson.success("0000", "success！");
            return returnJson;
        } else if (ObjectUtil.equal(batchUpdatePersonResponse.getCode(), 101012)) {
            BatchAddPersonRequest batchAddPersonRequest = new BatchAddPersonRequest();
            BatchAddPersonRequest.PersonListDTO personListDTO = new PersonListDTO();
            batchAddPersonRequest.getPersonList().add(personListDTO);
            personListDTO.setImageUri(imageUri);
            personListDTO.setName(htUpdatePersonRequest.getName());
            personListDTO.setUuid(updatePersonRequest.getPersonnelId());
            personListDTO.setOrgUuid(updatePersonRequest.getOrgId());
            personListDTO.setType(Optional.ofNullable(HTConstant.personTypes.get(updatePersonRequest.getPersonType())).orElse(1));
            BatchAddPersonResponse batchAddPersonResponse = HT_DEVICE_POST.postJson(HTConstant.batchAddPerson, updatePersonRequest.getIp(), updatePersonRequest.getPort(), batchAddPersonRequest, BatchAddPersonResponse.class);
            if (ObjectUtil.equal(batchAddPersonResponse.getCode(), 0)) {
                if (CollectionUtils.isNotEmpty(batchAddPersonResponse.getData().getSuccesses())) {
                    ReturnJson returnJson = new ReturnJson();
                    returnJson.success("0000", "success！");
                    return returnJson;
                } else {
                    throw new ServiceException(
                            500,
                            personListDTO.getName() + " 失败信息： code:"
                                    + batchAddPersonResponse.getCode()
                                    + " message:  批量添加人员失败！"
                                    + JSON.toJSONString(batchAddPersonResponse));
                }

            } else {
                throw new ServiceException(
                        500,
                        personListDTO.getName() + " 失败信息： code:"
                                + batchAddPersonResponse.getCode()
                                + " message:  "
                                + JSON.toJSONString(batchAddPersonResponse));
            }
        } else {
            throw new ServiceException(
                    500,
                    updatePersonRequest.getName() + " 失败信息： code:"
                            + batchUpdatePersonResponse.getCode()
                            + " message:  "
                            + JSON.toJSONString(batchUpdatePersonResponse));
        }
    }

    @Override
    public GetPersonResponse getPerson(String uri, GetPersonRequest getPersonRequest) throws Exception {
        return null;
    }

    @Override
    public GetPersonResponse listPerson(String uri, GetPersonRequest request) throws Exception {
        return null;
    }

    @Override
    public BaseResponse setUserPwd(String uri, SetUserPwdRequest setUserPwdRequest, RequestHeader requestHeader)
            throws Exception {
        return null;
    }

    @Override
    public BaseResponse setFactoryDefault(
            String uri, SetFactoryDefaultRequest setFactoryDefaultRequest, RequestHeader requestHeader)
            throws IOException, Exception {
        return null;
    }

    @Override
    public BaseResponse setSysTime(String uri, SetSysTimeRequest setSysTimeRequest, RequestHeader requestHeader)
            throws Exception {
        return null;
    }

    @Override
    public BaseResponse openDoor(String uri, OpenDoorRequest setSysTimeRequest, RequestHeader requestHeader)
            throws Exception {
        return null;
    }

    @Override
    public GetAndSetGeneralParamRequest getGeneralParam(String uri, RequestHeader requestHeader)
            throws Exception {
        return null;
    }

    @Override
    public GetAndSetDoorCondition getDoorCondition(String uri, RequestHeader requestHeader) throws Exception {
        return null;
    }

    @Override
    public BaseResponse setDoorCondition(String uri, GetAndSetDoorCondition getAndSetDoorCondition, RequestHeader requestHeader) throws Exception {
        return null;
    }

    @Override
    public GetAndSetSoundRequest getSound(String uri, RequestHeader requestHeader) throws Exception {
        return null;
    }

    @Override
    public BaseResponse setSound(String uri, GetAndSetSoundRequest getAndSetSoundRequest, RequestHeader requestHeader) throws Exception {
        return null;
    }

    @Override
    public BaseResponse setSubscribe(String uri, SetSubscribeRequest setSubscribeRequest, RequestHeader requestHeader) throws Exception {
        return null;
    }

    @Override
    public BaseResponse setGeneralParam(String uri, GetAndSetGeneralParamRequest getAndSetGeneralParamRequest, RequestHeader requestHeader) throws Exception {
        return null;
    }

    @Override
    public BaseResponse rebootDevice(String uri, RebootDeviceRequest rebootDeviceRequest, RequestHeader requestHeader) throws Exception {
        return null;
    }

}
